import { useMemo, useImperativeHandle, ForwardRefRenderFunction } from 'react';
import { createSchemaField, FormProvider } from '@formily/react';
import components from './schema-components-registed/components-biz';
import _ from 'lodash';
import useForm from '@/components/schema-form-render/hooks';

const SchemaField = createSchemaField(
  _.merge({
    components: {
      ...components,
    },
  }),
);

const SchemaFormRender: ForwardRefRenderFunction<any, any> = (
  { createSchemaFieldConfig, formConfig, form, schema },
  ref,
) => {
  const [wrapForm] = useForm(formConfig, form);

  console.log(wrapForm, form);

  useImperativeHandle(ref, () => wrapForm);

  const SchemaField1 = useMemo(
    () =>
      createSchemaField(
        _.merge(
          {
            components,
          },
          createSchemaFieldConfig,
        ),
      ),
    [createSchemaFieldConfig],
  );

  console.log(SchemaField, SchemaField1);

  return (
    <FormProvider form={wrapForm}>{SchemaField && <SchemaField schema={schema} />}</FormProvider>
  );
};

export { SchemaFormRender, useForm };
